package main

import (
	"archive/zip"
	"fmt"
	"gofile/mysftp"
	"gofile/myssh"
	"io"
	"log"
	"os"
	"os/exec"
)

// 压缩文件
func CompressedFile(file *os.File, prefix string, zw *zip.Writer) error {
	info, err := file.Stat()
	if err != nil || info.IsDir() {
		return err
	}
	header, err := zip.FileInfoHeader(info)
	if err != nil {
		return err
	}
	header.Name = prefix + "/" + header.Name
	writer, err := zw.CreateHeader(header)
	if err != nil {
		return err
	}
	if _, err = io.Copy(writer, file); err != nil {
		return err
	}
	return nil
}

// 压缩目录
func CompressedDir(file *os.File, prefix string, zw *zip.Writer) error {
	info, _ := file.Stat()
	prefix = prefix + "/" + info.Name()
	dirInfo, err := file.Readdir(-1)
	if err != nil {
		return err
	}
	for _, f := range dirInfo {
		f, err := os.Open(file.Name() + "/" + f.Name())
		if err != nil {
			return err
		}
		err = Compress(f, prefix, zw)
		if err != nil {
			return err
		}
	}
	return nil
}

// Compress 压缩文件
func Compress(file *os.File, prefix string, zw *zip.Writer) error {
	info, err := file.Stat()
	if err != nil {
		return err
	}
	// 如果是目录调用CompressedDir
	if info.IsDir() {
		return CompressedDir(file, prefix, zw)
	}
	// 如果是文件调用CompressedFile
	return CompressedFile(file, prefix, zw)
}

// 打包vue并压缩
func buildFront() {
	// 设置工作目录
	os.Chdir("./vue")

	// 打成dist
	cmd := exec.Command("powershell", "npm run build")
	output, err := cmd.Output()
	if err != nil {
		fmt.Println("could not run command: ", err)
	}
	fmt.Println(string(output))

	f, _ := os.Open("./dist")
	// 压缩文件
	dst, _ := os.Create("dist.zip")
	zipWriter := zip.NewWriter(dst)
	if err := Compress(f, "", zipWriter); err != nil {
		log.Fatalln(err.Error())
	}
	// Make sure to check the error on Close.
	if err := zipWriter.Close(); err != nil {
		log.Fatalln(err.Error())
	}
}

func main() {
	buildFront()
	mysftp.Upload()
	myssh.SshShell()
}
